﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using SlamCms;

namespace SlamCms.Data
{
    public class QueryPagedResult<T> : IEnumerable<T> where T : ContentItem
    {
        private List<T> results;

        public QueryPagedResult(QueryResult<T> source, int pageNumber, int pageSize = 10)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            if (pageNumber <= 0)
                throw new ArgumentNullException("pageNumber");

            if (pageSize <= 0)
                throw new ArgumentNullException("pageSize");

            this.TotalCount = source.Count();
            this.PageSize = pageSize;
            this.PageNumber = pageNumber;
            this.TotalPages = 1;
            this.CalculatePages();
            this.results = source.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();
        }

        public int NextPage 
        {
            get 
            {
                return this.PageNumber + 1;
            }
        }

        public int PreviousPage 
        {
            get 
            {
                return this.PageNumber - 1;
            }
        }

        public int TotalCount { get; protected set; }
        public int TotalPages { get; protected set; }
        public int PageNumber { get; protected set; }
        public int PageSize { get; protected set; }

        public bool HasPreviousPage()
        {
            return this.PageNumber > 0;
        }

        public bool HasNextPage()
        {
            return ((this.PageNumber - 1) * PageSize) <= TotalCount;
        }

        public bool IsCurrentPage(int pageNumber) 
        {
            return pageNumber == this.PageNumber;
        }

        public IEnumerator<T> GetEnumerator()
        {
            return this.results.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.results.GetEnumerator();
        }

        protected void CalculatePages()
        {
            if (this.PageSize > 0 && this.TotalCount > this.PageSize)
            {
                this.TotalPages = this.TotalCount / this.PageSize;
                if (this.TotalCount % this.PageSize > 0)
                    this.TotalPages++;
            }
        }
    }
}
